﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace WebCrawler.HttpConnection
{
    public class HttpTcpClient
    {
        private int _timeout = 1000;

        /// <summary>
        /// Receive and return Http content from tcp connection.
        /// </summary>
        public string Receive(string url)
        {
            string page = "";
            try
            {
                Uri uri = new Uri(url);
                using (TcpClient client = new TcpClient(uri.Host, uri.Port))
                {
                    client.ReceiveTimeout = _timeout;
                    using (NetworkStream ns = client.GetStream())
                    {
                        // Send request to server
                        string request = "GET /" + uri.PathAndQuery + " HTTP/1.1\r\n Host: " + uri.Host + "\r\nConnection: Close\r\n\r\n";
                        byte[] buffer = Encoding.ASCII.GetBytes(request);
                        ns.Write(buffer, 0, buffer.Length);

                        // Content description
                        page = "Default HTML page on " + uri.Host + ":\n\r\n";

                        // Receive response from server
                        buffer = new byte[client.ReceiveBufferSize];
                        int bytes = 0;
                        do
                        {
                            bytes = ns.Read(buffer, 0, buffer.Length);
                            page += Encoding.ASCII.GetString(buffer, 0, bytes);
                        } while (bytes > 0);
                    } // close stream
                } // close tcp
            }
            catch (Exception e)
            {
                page = e.Message;
            }
            return page;
        }

    }
}
